/**
 * 获取提现详情接口
 */

//引入Q模块
let Q = require('q');
//引入公共函数
let util = require('../../util');

let index = function(getData, postData, config, _redis, db) {
	let deferred = Q.defer();
	if(postData.withdrawCashId && postData.orderDate) {
		let withdrawCashOrderList = [];
		let withdrawCashLogs = [];
		let withdrawCashTotal = 0;
		let startTimestamp = new Date(postData.orderDate).getTime() / 1000;
		db.select('storeOrder', {
			withdrawCashId: postData.withdrawCashId,
			payMode: 'wxPay'
		}).then(function(orderList) {
			if(orderList.length == 0) {
				//未找到此提现ID的订单
				deferred.reject('-0132');
				return deferred.promise;
			}
			else {
				for(let orderIndex in orderList) {
					let {goodsList, timestamp} = orderList[orderIndex];
					if(timestamp > startTimestamp - 1 && timestamp < startTimestamp + 86401) {
						console.log(orderList[orderIndex]);
						withdrawCashOrderList.push(orderList[orderIndex]);
					}
					for(let goodsIndex in goodsList) {
						let {foodPrice, goodsPrice} = goodsList[goodsIndex];
						withdrawCashTotal += foodPrice || goodsPrice;
					}
					if(orderIndex == orderList.length - 1) {
						return db.connectDB('common');
					}
				}
			}
		}, function() {
			//查找有提现ID的订单失败
			deferred.reject('-0130');
		}).then(function(commonDB) {
			return commonDB.select('withdrawCashLogs', {
				withdrawCashId: postData.withdrawCashId
			});
		}, function() {
			//连接公共数据库失败
			deferred.reject('-0127');
		}).then(function(_withdrawCashLogs) {
			withdrawCashLogs = _withdrawCashLogs;
			if(withdrawCashLogs.length > 0) {
				withdrawCashLogs = withdrawCashLogs[0];
				return db.select('allowServices', {
					id: withdrawCashLogs.userId
				});
			}
			else {
				//未找到此提现ID的提现记录
				deferred.reject('-0133');
			}
		}, function() {
			//在公共数据库中查找提现记录失败
			deferred.reject('-0131');
		}).then(function(userData) {
			let userName = 'unknown';
			if(userData) {
				userName = userData[0].name;
			}
			deferred.resolve({
				userName: userName,
				withdrawCashOrderList: withdrawCashOrderList,
				withdrawCashLogs: withdrawCashLogs,
				withdrawCashTotal: withdrawCashTotal
			});
		}, function() {
			//查询提现者时出现错误
			deferred.reject('-0134');
		});
	}
	else {
		//查询提现详情接口参数不足
		deferred.reject('-0129');
	}
	return deferred.promise;
}

module.exports = {
	index: index
}